package org.example.rubbish.controller;


import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.example.rubbish.common.PageResult;
import org.example.rubbish.dto.ProductQuery;
import org.example.rubbish.entity.Product;
import org.example.rubbish.result.Result;
import org.example.rubbish.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;



@Validated
@RestController
@RequestMapping("/api/admin/products")
@RequiredArgsConstructor
public class ProductController {

    @Autowired
    private  ProductService productService;

    /**
     * 获取商品列表
     */
    @GetMapping
    public Result<PageResult<Product>> getProductList(@Valid ProductQuery query) {
        PageResult<Product> result = productService.getProductList(query);
        if (result.getRecords() != null && !result.getRecords().isEmpty()) {
            Product p = result.getRecords().get(4);
            System.out.println("images 类型: " + p.getImages().getClass().getName());
            System.out.println("images 内容: " + p.getImages());
        }
        return Result.success(result);
    }

    /**
     * 根据ID获取商品
     */
    @GetMapping("/{id}")
    public Result<Product> getProductById(@PathVariable Long id) {
        Product product = productService.getProductById(id);
        return Result.success(product);
    }

    /**
     * 添加商品
     */
    @PostMapping
    public Result<Void> addProduct(@Valid @RequestBody Product product) {
        productService.addProduct(product);
        return Result.success();
    }

    /**
     * 更新商品
     */
    @PutMapping("/{id}")
    public Result<Void> updateProduct(@PathVariable Long id, @Valid @RequestBody Product product) {
        product.setId(id);
        productService.updateProduct(product);
        return Result.success();
    }

    /**
     * 删除商品
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteProduct(@PathVariable Long id) {
        productService.deleteProduct(id);
        return Result.success();
    }

    /**
     * 上架/下架商品
     */
    @PatchMapping("/{id}/status")
    public Result<Void> updateProductStatus(@PathVariable Long id, @RequestParam Integer status) {
        productService.updateProductStatus(id, status);
        return Result.success();
    }
}